/*
 * crc16.c
 *
 *  Created on: 18 May 2015
 *      Author: yiqi.pan
 */
#include "crc16.h"

/*
    Optimized CRC-XMODEM calculation.

    Polynomial: x^16 + x^12 + x^5 + 1 (0x1021)<br>
    Initial value: 0x0

    This is the CRC used by the Xmodem-CRC protocol.

    The following is the equivalent functionality written in C.
*/

uint16_t crc_xmodem_update (uint16_t crc, uint8_t data)
{
	int i;

	crc = crc ^ ((uint16_t)data << 8);
	for (i=0; i<8; i++)
	{
		if (crc & 0x8000)
			crc = (crc << 1) ^ 0x1021;
		else
			crc <<= 1;
	}

	return crc;
}


void crc16_buffer(uint8_t* buffer, uint8_t bufflength, uint16_t* crc)
{
    uint8_t bc = 0;

    for ( ; bufflength > 0; bufflength--)
    {
        *crc = crc_xmodem_update(*crc, *(buffer+ bc));
        bc++;
    }
}
